package com.ztesoft.train.ssh.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.dao.DataAccessException;

/**
 * implement the base method
 * @author ztesoft
 *
 */
public abstract class AbstractDao implements DaoInterface {
//	private static final Logger logger = Logger.getLogger(AbstractDao.class.getName() );
	
	private EntityManager entityManager;
	/**
	 * return the entity class, XYZ.class
	 * @return
	 */
	protected abstract Class getEntityClass();
	/**
	 * return the entity name query name, defined in the entity file
	 * @return
	 */
	protected abstract String getNameQueryName();
	/**
	 * return the entity name query parameter name, defined in the entity file
	 * @return
	 */
	protected abstract String getNameQueryParamName();

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		
		this.entityManager = entityManager;
		
	}


	@Override
	public Object findbyId(Object id) throws DataAccessException {
		
		Object entity = null ;
		
		TypedQuery<Object> query =  entityManager.createNamedQuery(getNameQueryName(), this.getEntityClass());
		
		query.setParameter(getNameQueryParamName(), id);
		
		try {
			
			entity = query.getSingleResult() ;
			
			
		} catch (javax.persistence.NoResultException ex) {
			
//			logger.warn("No " + getEntityClass() + " was found with an " + this.getNameQueryParamName() + " of " + id);
			
		}
		
		return entity;
		
	}


	@Override
	public List<?> findAll() {
		
		
		TypedQuery<?> query = entityManager.createQuery("from " + this.getEntityClass().getName(), this.getEntityClass());
		
		List<?> entities = query.getResultList();
		
		return entities;

	}


	@Override
	public void update(Object entity) {
	
		entityManager.merge(entity);
		
		
	}

	@Override
	public void delete(Object entity) {
		//use merge to get the Person object into
		//this persistence context
		Object deleteEntity = entityManager.merge(entity);
		entityManager.remove(deleteEntity);
	}


	@Override
	public void save(Object entity) {
		entityManager.persist(entity);
		
	}


	

}
